package dr.server.impl.sms.aliyun;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import dr.common.ResultModel;
import dr.common.i18n.ResKit;
import dr.common.utils.AliyunSmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AliyunSmsService {

    @Autowired
    AliyunSmsUtil aliyunSmsUtil;

    public ResultModel sendSms(String mobile, String TemplateCode, String json) {
        String value = "";
        try {
            log.info("mobile:{},TemplateCode:{},json:{}",mobile,TemplateCode,json);
            value = aliyunSmsUtil.sendSms(mobile, TemplateCode, json);
            if(!StrUtil.isNotEmpty(value)){
                return ResultModel.fail(ResKit.getMsg("send_err"));
            }
            JSONObject parse = JSONObject.parseObject(value);
            if("isv.MOBILE_NUMBER_ILLEGAL".equals(parse.getString("Code"))){
                return ResultModel.fail(ResKit.getMsg("send_mobile_input_err"));
            }
            if (!parse.getString("Code").equals("OK")) {
                return ResultModel.fail(value);
            }
        }catch (Exception e) {
            return ResultModel.fail(e.getLocalizedMessage() + "-" + value);
        }

        return ResultModel.ok();
    }

    /**
     * 发送短信通过后台短信模板发送
     * @param mobile    手机号
     * @param key       模板key
     * @param json      短信参数
     * @return
     */
    public ResultModel sendSmsByKey(String mobile, String key, String json) {
        // 通过key查询模板信息
        Record record = Db.findFirst("SELECT `code` FROM dr_sms_template WHERE `key` = ? and verify_status = 1", key);
        if (record == null) {
            return ResultModel.fail("发送失败，通过key【" + key + "】没有找到对应的短信模板");
        }
        String templateCode = record.getStr("code");
        return sendSms(mobile, templateCode, json);
    }
}
